import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class HotelsPage extends StatefulWidget {
  const HotelsPage({super.key});

  @override
  State<HotelsPage> createState() => _HotelsPageState();
}

class _HotelsPageState extends State<HotelsPage> {
  final Dio _dio = Dio();
  List<Map<String, dynamic>> _hotels = [];
  List<Map<String, dynamic>> _filteredHotels = [];
  bool _isLoading = true;
  String _selectedCity = '全部';
  int _selectedStarRating = 0;
  String _searchQuery = '';

  final List<String> _cities = ['全部', '成都', '丽江', '三亚', '西安', '桂林', '青岛'];
  final List<String> _starRatings = ['全部', '5星级', '4星级', '3星级'];

  @override
  void initState() {
    super.initState();
    _loadHotels();
  }

  Future<void> _loadHotels() async {
    try {
      setState(() => _isLoading = true);

      final response = await _dio.get(
        'http://localhost:5000/api/hotels',
        queryParameters: {'limit': 20, 'sortBy': 'rating', 'sortOrder': 'desc'},
      );

      if (response.statusCode == 200 && response.data['success']) {
        setState(() {
          _hotels = List<Map<String, dynamic>>.from(response.data['data']);
          _filterHotels();
          _isLoading = false;
        });
      }
    } catch (e) {
      print('加载酒店数据失败: $e');
      setState(() => _isLoading = false);
    }
  }

  void _filterHotels() {
    _filteredHotels =
        _hotels.where((hotel) {
          bool matchesCity =
              _selectedCity == '全部' || hotel['city'] == _selectedCity;
          bool matchesStarRating =
              _selectedStarRating == 0 ||
              hotel['starRating'] == _selectedStarRating;
          bool matchesSearch =
              _searchQuery.isEmpty ||
              hotel['name'].toString().toLowerCase().contains(
                _searchQuery.toLowerCase(),
              ) ||
              hotel['city'].toString().toLowerCase().contains(
                _searchQuery.toLowerCase(),
              ) ||
              hotel['description'].toString().toLowerCase().contains(
                _searchQuery.toLowerCase(),
              );

          return matchesCity && matchesStarRating && matchesSearch;
        }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          _buildSliverAppBar(),
          SliverToBoxAdapter(
            child: Column(
              children: [_buildSearchSection(), _buildFilterSection()],
            ),
          ),
          _isLoading
              ? const SliverFillRemaining(
                child: Center(child: CircularProgressIndicator()),
              )
              : _filteredHotels.isEmpty
              ? const SliverFillRemaining(child: Center(child: Text('暂无酒店数据')))
              : SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) => _buildHotelCard(_filteredHotels[index]),
                  childCount: _filteredHotels.length,
                ),
              ),
        ],
      ),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 200,
      floating: false,
      pinned: true,
      backgroundColor: Colors.green[600],
      flexibleSpace: FlexibleSpaceBar(
        title: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.hotel, color: Colors.white, size: 24),
            const SizedBox(width: 8),
            const Text(
              '酒店预订',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        background: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Colors.green[400]!, Colors.green[600]!],
            ),
          ),
          child: const Center(
            child: Icon(Icons.hotel, size: 80, color: Colors.white70),
          ),
        ),
      ),
    );
  }

  Widget _buildSearchSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: TextField(
        decoration: InputDecoration(
          hintText: '搜索酒店名称或城市...',
          prefixIcon: const Icon(Icons.search),
          suffixIcon:
              _searchQuery.isNotEmpty
                  ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      setState(() {
                        _searchQuery = '';
                        _filterHotels();
                      });
                    },
                  )
                  : null,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(25)),
          filled: true,
          fillColor: Colors.grey[100],
        ),
        onChanged: (value) {
          setState(() {
            _searchQuery = value;
            _filterHotels();
          });
        },
      ),
    );
  }

  Widget _buildFilterSection() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Expanded(child: _buildCityFilter()),
          const SizedBox(width: 12),
          Expanded(child: _buildStarRatingFilter()),
        ],
      ),
    );
  }

  Widget _buildCityFilter() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: _selectedCity,
          isExpanded: true,
          icon: const Icon(Icons.location_city),
          hint: const Text('选择城市'),
          onChanged: (String? newValue) {
            setState(() {
              _selectedCity = newValue!;
              _filterHotels();
            });
          },
          items:
              _cities.map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
        ),
      ),
    );
  }

  Widget _buildStarRatingFilter() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[300]!),
        borderRadius: BorderRadius.circular(8),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<int>(
          value: _selectedStarRating,
          isExpanded: true,
          icon: const Icon(Icons.star),
          hint: const Text('星级'),
          onChanged: (int? newValue) {
            setState(() {
              _selectedStarRating = newValue!;
              _filterHotels();
            });
          },
          items: [
            const DropdownMenuItem<int>(value: 0, child: Text('全部')),
            const DropdownMenuItem<int>(value: 5, child: Text('5星级')),
            const DropdownMenuItem<int>(value: 4, child: Text('4星级')),
            const DropdownMenuItem<int>(value: 3, child: Text('3星级')),
          ],
        ),
      ),
    );
  }

  Widget _buildHotelCard(Map<String, dynamic> hotel) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 酒店图片
          ClipRRect(
            borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
            child: Stack(
              children: [
                Image.network(
                  hotel['mainImage'] ?? 'https://via.placeholder.com/400x200',
                  height: 200,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      height: 200,
                      color: Colors.grey[300],
                      child: const Icon(
                        Icons.hotel,
                        size: 50,
                        color: Colors.grey,
                      ),
                    );
                  },
                ),
                // 热门标签
                if (hotel['isPopular'] == true)
                  Positioned(
                    top: 12,
                    left: 12,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: const Text(
                        '热门',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                // 星级
                Positioned(
                  top: 12,
                  right: 12,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 4,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Icon(Icons.star, color: Colors.amber, size: 16),
                        const SizedBox(width: 2),
                        Text(
                          '${hotel['starRating']}星',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 酒店信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 酒店名称和评分
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            hotel['name'] ?? '',
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 4),
                          Row(
                            children: [
                              Icon(
                                Icons.location_on,
                                size: 16,
                                color: Colors.grey[600],
                              ),
                              const SizedBox(width: 4),
                              Expanded(
                                child: Text(
                                  '${hotel['city']} • ${hotel['address']}',
                                  style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.grey[600],
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 12),
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Icon(Icons.star, color: Colors.white, size: 16),
                          const SizedBox(width: 2),
                          Text(
                            '${hotel['rating']?.toStringAsFixed(1)}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 12),

                // 酒店描述
                Text(
                  hotel['description'] ?? '',
                  style: TextStyle(fontSize: 14, color: Colors.grey[700]),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),

                const SizedBox(height: 12),

                // 设施
                if (hotel['amenities'] != null && hotel['amenities'].isNotEmpty)
                  Wrap(
                    spacing: 8,
                    runSpacing: 4,
                    children:
                        (hotel['amenities'] as List).take(4).map<Widget>((
                          amenity,
                        ) {
                          return Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.green[50],
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(color: Colors.green[200]!),
                            ),
                            child: Text(
                              amenity.toString(),
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.green[700],
                              ),
                            ),
                          );
                        }).toList(),
                  ),

                const SizedBox(height: 12),

                // 价格和预订按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (hotel['originalPrice'] != null &&
                            hotel['originalPrice'] > hotel['price'])
                          Text(
                            '¥${hotel['originalPrice']}',
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[500],
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        Row(
                          children: [
                            Text(
                              '¥${hotel['price']}',
                              style: const TextStyle(
                                fontSize: 24,
                                fontWeight: FontWeight.bold,
                                color: Colors.red,
                              ),
                            ),
                            const Text(
                              '/晚',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey,
                              ),
                            ),
                          ],
                        ),
                        if (hotel['discount'] != null)
                          Text(
                            hotel['discount'],
                            style: const TextStyle(
                              fontSize: 12,
                              color: Colors.red,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                      ],
                    ),
                    ElevatedButton(
                      onPressed: () {
                        _showHotelDetail(hotel);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green[600],
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 24,
                          vertical: 12,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                      child: const Text('预订'),
                    ),
                  ],
                ),

                // 评价信息
                if (hotel['reviewCount'] != null && hotel['reviewCount'] > 0)
                  Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(
                      '${hotel['reviewCount']} 条评价',
                      style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _showHotelDetail(Map<String, dynamic> hotel) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder:
          (context) => DraggableScrollableSheet(
            initialChildSize: 0.7,
            maxChildSize: 0.9,
            minChildSize: 0.5,
            builder:
                (context, scrollController) => Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(20),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 拖拽指示器
                      Container(
                        margin: const EdgeInsets.only(top: 8),
                        width: 40,
                        height: 4,
                        decoration: BoxDecoration(
                          color: Colors.grey[300],
                          borderRadius: BorderRadius.circular(2),
                        ),
                      ),

                      Expanded(
                        child: SingleChildScrollView(
                          controller: scrollController,
                          padding: const EdgeInsets.all(16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 酒店图片
                              ClipRRect(
                                borderRadius: BorderRadius.circular(12),
                                child: Image.network(
                                  hotel['mainImage'] ??
                                      'https://via.placeholder.com/400x200',
                                  height: 200,
                                  width: double.infinity,
                                  fit: BoxFit.cover,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Container(
                                      height: 200,
                                      color: Colors.grey[300],
                                      child: const Icon(
                                        Icons.hotel,
                                        size: 50,
                                        color: Colors.grey,
                                      ),
                                    );
                                  },
                                ),
                              ),

                              const SizedBox(height: 16),

                              // 酒店名称和星级
                              Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      hotel['name'] ?? '',
                                      style: const TextStyle(
                                        fontSize: 24,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                  Row(
                                    children: List.generate(
                                      hotel['starRating'] ?? 0,
                                      (index) => const Icon(
                                        Icons.star,
                                        color: Colors.amber,
                                        size: 20,
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              const SizedBox(height: 8),

                              // 地址
                              Row(
                                children: [
                                  Icon(
                                    Icons.location_on,
                                    size: 16,
                                    color: Colors.grey[600],
                                  ),
                                  const SizedBox(width: 4),
                                  Expanded(
                                    child: Text(
                                      hotel['address'] ?? '',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey[600],
                                      ),
                                    ),
                                  ),
                                ],
                              ),

                              const SizedBox(height: 16),

                              // 描述
                              Text(
                                hotel['description'] ?? '',
                                style: const TextStyle(fontSize: 16),
                              ),

                              const SizedBox(height: 16),

                              // 设施
                              if (hotel['amenities'] != null &&
                                  hotel['amenities'].isNotEmpty) ...[
                                const Text(
                                  '酒店设施',
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                Wrap(
                                  spacing: 8,
                                  runSpacing: 8,
                                  children:
                                      (hotel['amenities'] as List).map<Widget>((
                                        amenity,
                                      ) {
                                        return Container(
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 12,
                                            vertical: 6,
                                          ),
                                          decoration: BoxDecoration(
                                            color: Colors.green[50],
                                            borderRadius: BorderRadius.circular(
                                              16,
                                            ),
                                            border: Border.all(
                                              color: Colors.green[200]!,
                                            ),
                                          ),
                                          child: Text(
                                            amenity.toString(),
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.green[700],
                                            ),
                                          ),
                                        );
                                      }).toList(),
                                ),
                                const SizedBox(height: 16),
                              ],

                              // 联系信息
                              if (hotel['contact'] != null) ...[
                                const Text(
                                  '联系方式',
                                  style: TextStyle(
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 8),
                                if (hotel['contact']['phone'] != null)
                                  Row(
                                    children: [
                                      const Icon(Icons.phone, size: 16),
                                      const SizedBox(width: 8),
                                      Text(hotel['contact']['phone']),
                                    ],
                                  ),
                                if (hotel['contact']['email'] != null)
                                  Row(
                                    children: [
                                      const Icon(Icons.email, size: 16),
                                      const SizedBox(width: 8),
                                      Text(hotel['contact']['email']),
                                    ],
                                  ),
                                const SizedBox(height: 16),
                              ],

                              // 预订按钮
                              SizedBox(
                                width: double.infinity,
                                child: ElevatedButton(
                                  onPressed:
                                      () => _showHotelBookingDialog(hotel),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.green[600],
                                    foregroundColor: Colors.white,
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 16,
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                  ),
                                  child: Text(
                                    '立即预订 ¥${hotel['price']}/晚',
                                    style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
          ),
    );
  }

  void _showHotelBookingDialog(Map<String, dynamic> hotel) {
    final nameController = TextEditingController();
    final phoneController = TextEditingController();
    final emailController = TextEditingController();
    final remarksController = TextEditingController();
    DateTime checkInDate = DateTime.now().add(const Duration(days: 1));
    DateTime checkOutDate = DateTime.now().add(const Duration(days: 2));
    int roomCount = 1;

    showDialog(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder:
                (context, setDialogState) => AlertDialog(
                  title: const Text('酒店预订'),
                  content: SingleChildScrollView(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 联系人信息
                        TextField(
                          controller: nameController,
                          decoration: const InputDecoration(
                            labelText: '联系人姓名 *',
                            border: OutlineInputBorder(),
                          ),
                        ),
                        const SizedBox(height: 12),
                        TextField(
                          controller: phoneController,
                          decoration: const InputDecoration(
                            labelText: '联系电话 *',
                            border: OutlineInputBorder(),
                          ),
                          keyboardType: TextInputType.phone,
                        ),
                        const SizedBox(height: 12),
                        TextField(
                          controller: emailController,
                          decoration: const InputDecoration(
                            labelText: '邮箱地址 *',
                            border: OutlineInputBorder(),
                          ),
                          keyboardType: TextInputType.emailAddress,
                        ),
                        const SizedBox(height: 12),

                        // 入住日期
                        InkWell(
                          onTap: () async {
                            final date = await showDatePicker(
                              context: context,
                              initialDate: checkInDate,
                              firstDate: DateTime.now(),
                              lastDate: DateTime.now().add(
                                const Duration(days: 365),
                              ),
                            );
                            if (date != null) {
                              setDialogState(() {
                                checkInDate = date;
                                // 确保退房日期不早于入住日期
                                if (checkOutDate.isBefore(
                                  checkInDate.add(const Duration(days: 1)),
                                )) {
                                  checkOutDate = checkInDate.add(
                                    const Duration(days: 1),
                                  );
                                }
                              });
                            }
                          },
                          child: Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '入住日期: ${checkInDate.year}-${checkInDate.month.toString().padLeft(2, '0')}-${checkInDate.day.toString().padLeft(2, '0')}',
                                ),
                                const Icon(Icons.calendar_today),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),

                        // 退房日期
                        InkWell(
                          onTap: () async {
                            final date = await showDatePicker(
                              context: context,
                              initialDate: checkOutDate,
                              firstDate: checkInDate.add(
                                const Duration(days: 1),
                              ),
                              lastDate: DateTime.now().add(
                                const Duration(days: 365),
                              ),
                            );
                            if (date != null) {
                              setDialogState(() {
                                checkOutDate = date;
                              });
                            }
                          },
                          child: Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '退房日期: ${checkOutDate.year}-${checkOutDate.month.toString().padLeft(2, '0')}-${checkOutDate.day.toString().padLeft(2, '0')}',
                                ),
                                const Icon(Icons.calendar_today),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),

                        // 房间数量
                        Row(
                          children: [
                            const Text('房间数量: '),
                            IconButton(
                              onPressed:
                                  roomCount > 1
                                      ? () {
                                        setDialogState(() {
                                          roomCount--;
                                        });
                                      }
                                      : null,
                              icon: const Icon(Icons.remove),
                            ),
                            Text('$roomCount'),
                            IconButton(
                              onPressed: () {
                                setDialogState(() {
                                  roomCount++;
                                });
                              },
                              icon: const Icon(Icons.add),
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),

                        TextField(
                          controller: remarksController,
                          decoration: const InputDecoration(
                            labelText: '特殊需求 (可选)',
                            border: OutlineInputBorder(),
                          ),
                          maxLines: 3,
                        ),
                        const SizedBox(height: 16),

                        // 价格总计
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '住宿天数: ',
                                    style: TextStyle(fontSize: 14),
                                  ),
                                  Text(
                                    '${checkOutDate.difference(checkInDate).inDays} 晚',
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const Text(
                                    '总价: ',
                                    style: TextStyle(fontSize: 16),
                                  ),
                                  Text(
                                    '¥${(hotel['price'] * roomCount * checkOutDate.difference(checkInDate).inDays).toStringAsFixed(0)}',
                                    style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.red,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: const Text('取消'),
                    ),
                    ElevatedButton(
                      onPressed:
                          () => _submitHotelOrder(
                            hotel,
                            nameController.text,
                            phoneController.text,
                            emailController.text,
                            checkInDate,
                            checkOutDate,
                            roomCount,
                            remarksController.text,
                          ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,
                        foregroundColor: Colors.white,
                      ),
                      child: const Text('确认预订'),
                    ),
                  ],
                ),
          ),
    );
  }

  Future<void> _submitHotelOrder(
    Map<String, dynamic> hotel,
    String name,
    String phone,
    String email,
    DateTime checkInDate,
    DateTime checkOutDate,
    int roomCount,
    String remarks,
  ) async {
    // 验证输入
    if (name.isEmpty || phone.isEmpty || email.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请填写完整的联系信息'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    try {
      Navigator.pop(context); // 关闭对话框
      Navigator.pop(context); // 关闭详情页

      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(child: CircularProgressIndicator()),
      );

      final response = await _dio.post(
        'http://127.0.0.1:5000/api/orders/hotels',
        data: {
          'hotelId': hotel['_id'],
          'checkInDate': checkInDate.toIso8601String(),
          'checkOutDate': checkOutDate.toIso8601String(),
          'roomCount': roomCount,
          'customerInfo': {
            'name': name,
            'phone': phone,
            'email': email,
            'remarks': remarks.isNotEmpty ? remarks : null,
          },
          'specialRequests': remarks.isNotEmpty ? [remarks] : [],
        },
        options: Options(
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer demo_token', // 需要实际的token
          },
        ),
      );

      Navigator.pop(context); // 关闭加载指示器

      if (response.statusCode == 201 && response.data['success']) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('预订成功！您可以在"我的订单"中查看订单详情'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        throw Exception(response.data['message'] ?? '预订失败');
      }
    } catch (e) {
      Navigator.pop(context); // 关闭加载指示器
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('预订失败: ${e.toString()}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}
